/**
 * JSON数据存储服务
 * 替代SQLite的轻量级JSON存储方案，专为鸿蒙系统设计
 */
export interface JsonStorageOptions {
  storageKey: string;
  defaultValue?: any;
  encrypt?: boolean;
}

export class JsonStorageService {
  private static instance: JsonStorageService;
  private memoryCache: Map<string, any> = new Map();

  private constructor() {}

  static getInstance(): JsonStorageService {
    if (!JsonStorageService.instance) {
      JsonStorageService.instance = new JsonStorageService();
    }
    return JsonStorageService.instance;
  }

  /**
   * 保存数据到JSON存储
   */
  async save<T>(key: string, data: T): Promise<void> {
    try {
      // 先保存到内存缓存
      this.memoryCache.set(key, data);
      
      // 然后保存到localStorage
      const jsonString = JSON.stringify(data);
      localStorage.setItem(key, jsonString);
      
      console.log(`数据已保存到JSON存储: ${key}`);
    } catch (error) {
      console.error('保存数据失败:', error);
      throw new Error(`保存数据失败: ${key}`);
    }
  }

  /**
   * 从JSON存储加载数据
   */
  async load<T>(key: string, defaultValue?: T): Promise<T | null> {
    try {
      // 先检查内存缓存
      if (this.memoryCache.has(key)) {
        return this.memoryCache.get(key);
      }

      // 从localStorage加载
      const jsonString = localStorage.getItem(key);
      if (!jsonString) {
        return defaultValue || null;
      }

      const data = JSON.parse(jsonString);
      
      // 保存到内存缓存
      this.memoryCache.set(key, data);
      
      return data;
    } catch (error) {
      console.error('加载数据失败:', error);
      return defaultValue || null;
    }
  }

  /**
   * 删除数据
   */
  async remove(key: string): Promise<void> {
    try {
      this.memoryCache.delete(key);
      localStorage.removeItem(key);
      console.log(`数据已删除: ${key}`);
    } catch (error) {
      console.error('删除数据失败:', error);
      throw new Error(`删除数据失败: ${key}`);
    }
  }

  /**
   * 清空所有数据
   */
  async clear(): Promise<void> {
    try {
      this.memoryCache.clear();
      localStorage.clear();
      console.log('所有数据已清空');
    } catch (error) {
      console.error('清空数据失败:', error);
      throw new Error('清空数据失败');
    }
  }

  /**
   * 获取所有键名
   */
  async keys(): Promise<string[]> {
    try {
      return Object.keys(localStorage);
    } catch (error) {
      console.error('获取键名失败:', error);
      return [];
    }
  }

  /**
   * 检查键是否存在
   */
  async exists(key: string): Promise<boolean> {
    return localStorage.getItem(key) !== null;
  }

  /**
   * 导出所有数据为JSON文件
   */
  async exportData(): Promise<string> {
    const allData: Record<string, any> = {};
    const keys = await this.keys();
    
    for (const key of keys) {
      const data = await this.load(key);
      if (data !== null) {
        allData[key] = data;
      }
    }
    
    return JSON.stringify(allData, null, 2);
  }

  /**
   * 从JSON文件导入数据
   */
  async importData(jsonString: string): Promise<void> {
    try {
      const allData = JSON.parse(jsonString);
      
      for (const [key, data] of Object.entries(allData)) {
        await this.save(key, data);
      }
      
      console.log('数据导入成功');
    } catch (error) {
      console.error('导入数据失败:', error);
      throw new Error('导入数据失败');
    }
  }

  /**
   * 获取存储统计信息
   */
  async getStorageStats(): Promise<{
    totalKeys: number;
    totalSize: number;
    keys: string[];
  }> {
    const keys = await this.keys();
    let totalSize = 0;
    
    for (const key of keys) {
      const value = localStorage.getItem(key);
      if (value) {
        totalSize += new Blob([value]).size;
      }
    }
    
    return {
      totalKeys: keys.length,
      totalSize,
      keys
    };
  }
}

export const jsonStorage = JsonStorageService.getInstance();